from PyQt5.QtWidgets import QMainWindow, QHeaderView, QMessageBox
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import QStringListModel, QDate, Qt
import UI.log_manager_UI as log_manger_UI
import typeManager
import printer
import itemEditor
import constants
import json
import sys


class LogManagerUI(QMainWindow, log_manger_UI.Ui_Dialog):
    def __init__(self):
        super(LogManagerUI, self).__init__()
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.setupUi(self)
        self.dataList = []
        self.dynamic_dataList = []
        self.stringList = []
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableViewModel = QStandardItemModel(self)
        self.tableView.setModel(self.tableViewModel)
        self.comboBoxModel = QStringListModel(self)
        self.comboBoxModel.setStringList(['选择', '入库模式', '出库模式', '结余模式'])
        self.comboBox.setModel(self.comboBoxModel)
        self.dateEdit.setDate(QDate().currentDate())
        self.reload()

    def enter(self):
        item_editor_ui = itemEditor.ItemEditorUI()
        item_editor_ui.exec_()
        self.reload()

    def out(self):
        item_editor_ui = itemEditor.ItemEditorUI(is_out=True)
        item_editor_ui.exec_()
        self.reload()

    def remove(self):
        buttons = QMessageBox.StandardButton
        rlt = QMessageBox.warning(self, '警告', '确认删除此项?', buttons.Yes | buttons.No, buttons.No)
        if rlt == buttons.No:
            return
        indexes = self.tableView.selectedIndexes()
        for index in indexes:
            self.dataList.remove(self.dynamic_dataList[index.row()])
            break
        self.save()
        self.reload()

    def reload(self):
        mode = self.comboBoxModel.stringList()[self.comboBox.currentIndex()]
        text = self.searchLineEdit.text()
        disable_date_filter = not self.checkBox.isChecked()
        date_string = self.dateEdit.date().toString('yyyy/MM/dd')
        if text == '':
            text = None
        self.stringList = []
        self.dataList = []
        self.tableViewModel.clear()
        try:
            with open('logData.json', 'r') as f:
                self.dataList = json.load(f)
        except json.JSONDecodeError as err:
            print("JSONDecodeError: {0}".format(err))
        except IOError as err:
            print("IOError: {0}".format(err))
        self.tableViewModel.setHorizontalHeaderLabels(['货物类型', '数量', '单价(元)', '总价(元)', '日期', '状态'])
        self.dynamic_dataList = []
        strict_mode = True
        if mode == '结余模式':
            strict_mode = False
            self.out_button.setDisabled(True)
            self.enter_button.setDisabled(True)
            self.delete_button.setDisabled(True)
            printer.data_filter = QDate.currentDate().toString('yyyy/MM/dd')
            self.dataList = printer.get_print_data(printer.init(), mode)
        else:
            self.out_button.setEnabled(True)
            self.enter_button.setEnabled(True)
            self.delete_button.setEnabled(True)
        printer.data_filter = date_string
        for item in self.dataList:
            if ((mode == '入库模式' and item['mode'] == 1) or (
                    mode == '出库模式' and item['mode'] == -1) or mode == '选择' or mode == '结余模式') \
                    and ((text is None) or (text in item['kind'])) and (
                    disable_date_filter or printer.date_checker(item['date'], no_today=False, strict_mode=strict_mode)):
                columns = [QStandardItem('%s' % item['kind']),
                           QStandardItem('%.2f(%s)' % (item['number'], item['unit'])),
                           QStandardItem('%.2f' % item['unitPrice']),
                           QStandardItem('%.2f' % (item['unitPrice'] * item['number'])),
                           QStandardItem('%s' % item['date']),
                           QStandardItem('%s' % constants.logModes[item['mode']])]
                if mode == '结余模式':
                    columns.pop(len(columns) - 1)
                    columns.append(QStandardItem('结余模式'))
                self.tableViewModel.appendRow(columns)
                self.dynamic_dataList.append(item)

    def save(self):
        try:
            with open('logData.json', 'w') as f:
                json.dump(self.dataList, f)
        except json.JSONDecodeError as err:
            print('JSONDecodeError: {0}'.format(err))
        except IOError as err:
            print('IOError: {0}'.format(err))

    def show_print(self):
        if not self.checkBox.isChecked():
            QMessageBox.critical(self, '错误', '若要进行打印，则必须指定日期')
            return
        # QMessageBox.warning(self, '警告', '打印时文字筛选将被忽略') disable because text filter is now available
        mode = self.comboBoxModel.stringList()[self.comboBox.currentIndex()]
        if mode == '选择':
            QMessageBox.critical(self, '错误', '打印之前，必须选择一个模式')
            return
        date_string = self.dateEdit.date().toString('yyyy/MM/dd')
        printer.mode = mode
        printer.data_filter = date_string
        printer.text_filter = self.searchLineEdit.text()
        printer.PrinterUi().print_now()

    @staticmethod
    def show_type_edit():
        type_manager = typeManager.TypeManagerUi()
        type_manager.exec_()

    @staticmethod
    def exit():
        sys.exit(0)
